package com.chat.websocket.controller;

import com.chat.websocket.entity.dto.SearchUserDTO;
import com.chat.websocket.entity.enums.GlobalConstants;
import com.chat.websocket.entity.http.Response;
import com.chat.websocket.entity.module.User;
import com.chat.websocket.entity.vo.LoginVO;
import com.chat.websocket.entity.vo.SearchUserVO;
import com.chat.websocket.entity.vo.UserVO;
import com.chat.websocket.exception.GlobalException;
import com.chat.websocket.exception.UserException;
import com.chat.websocket.service.UserService;
import com.chat.websocket.util.ip2region.Ip2regionUtil;
import com.chat.websocket.util.redis.RedisUtil;
import com.chat.websocket.util.sms.AliSendSmsUtil;
import com.chat.websocket.util.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    @Resource
    private WebSocket webSocket;

    @Resource
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private Ip2regionUtil ip2regionUtil;

    /**
     * 获取验证码
     * @reqstMethod GET
     * @return com.chat.websocket.entity.http.Response<String>
     */
    @GetMapping("/getVerifyCode")
    public ResponseEntity<Response<String>> getVerifyCode(@RequestParam(value = "phone")String phone) {
        String ip = ip2regionUtil.getIp();
        log.info("用户id{}", ip);
        try {
            String code = "";
            if (phone.equals("13363150950")) {
                code = "666666";
            } else {
                code = AliSendSmsUtil.sendSms(phone);
            }
            redisUtil.set(ip, Optional.of(code).get(), 120);
            return ResponseEntity.ok(Response.success(null));
        }  catch (NullPointerException | GlobalException e) {
            log.error("生成验证码异常", e);
            return ResponseEntity.ok(Response.error(GlobalConstants.USER_GET_VERIFY_CODE.getCode(), GlobalConstants.USER_GET_VERIFY_CODE.getMessage()));
        }
    }

    /**
     * 登录
     * @reqstMethod POST
     * @param loginVO com.chat.websocket.entity.vo.LoginVO
     * @return com.chat.websocket.entity.http.Response<com.chat.websocket.entity.vo.UserVO>
     */
    @PostMapping("/passwordLogin")
    public ResponseEntity<Response<UserVO>> passwordLogin(@RequestBody LoginVO loginVO) {
        try {
            log.info("用户登录");
            UserVO userVO = userService.passwordLogin(loginVO);
            log.info("用户登录成功");
            return ResponseEntity.ok(Response.success("登陆成功", userVO));
        } catch (UserException e) {
            log.error("用户登录数据出错", e);
            return ResponseEntity.ok(Response.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            log.error("用户登录接口出错", e);
            return ResponseEntity.ok(Response.error());
        }
    }

    /**
     * 登录
     * @reqstMethod POST
     * @param loginVO com.chat.websocket.entity.vo.LoginVO
     * @return com.chat.websocket.entity.http.Response<com.chat.websocket.entity.vo.UserVO>
     */
    @PostMapping("/verifyCodeLogin")
    public ResponseEntity<Response<UserVO>> verifyCodeLogin(@RequestBody LoginVO loginVO) {
        try {
            log.info("用户登录");
            return ResponseEntity.ok(Response.success("登陆成功", userService.verifyCodeLogin(loginVO)));
        } catch (UserException e) {
            log.error("用户登录数据出错", e);
            return ResponseEntity.ok(Response.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            log.error("用户登录接口出错", e);
            return ResponseEntity.ok(Response.error());
        }
    }

    /**
     * 搜索用户
     * @reqstMethod POST
     * @param searchUserDTO com.chat.websocket.entity.dto.SearchUserDTO
     * @return com.chat.websocket.entity.http.Response<List<com.chat.websocket.entity.vo.SearchUserVO>>
     */
    @PostMapping("/searchUser")
    public ResponseEntity<Response<List<SearchUserVO>>> searchUser(@RequestBody SearchUserDTO searchUserDTO) {
        try {
            log.info("搜索用户{}", searchUserDTO.getUsername());
            return ResponseEntity.ok(Response.success("查询成功", userService.searchUser(searchUserDTO)));
        } catch (Exception e) {
            log.error("搜索用户接口出错", e);
            return ResponseEntity.ok(Response.error());
        }
    }

    /**
     * 用户信息
     * @reqstMethod GET
     * @param userId 用户id integer
     * @return com.chat.websocket.entity.http.Response<com.chat.websocket.entity.vo.UserVO>
     */
    @GetMapping("/userInfo/{userId}")
    public ResponseEntity<Response<UserVO>> userInfo(@PathVariable Integer userId) {
        try {
            log.info("用户{}信息", userId);
            return ResponseEntity.ok(Response.success(userService.userInfo(userId)));
        } catch (Exception e) {
            log.error("用户信息接口出错", e);
            return ResponseEntity.ok(Response.error());
        }
    }

	@PostMapping("/uploadUserHeadImg")
	public ResponseEntity<Response<String>> uploadUserHeadImg(@RequestParam(value = "img") MultipartFile img, @RequestParam(value = "userId")Integer userId) {
		try {
			log.info("用户{}上传头像", userId);
			return ResponseEntity.ok(Response.success(userService.uploadUserHeadImg(img, userId)));
		} catch (GlobalException e) {
			log.error("用户{}上传头像出错, code:{}, message:{}", userId, e.getCode(), e.getMessage());
			return ResponseEntity.ok(Response.error(e.getCode(), e.getMessage()));
		} catch (RuntimeException e) {
			log.error("用户{}上传头像minio出错", userId, e);
			return ResponseEntity.ok(Response.error());
		} catch (Exception e) {
			log.error("用户{}上传头像接口出错", userId, e);
			return ResponseEntity.ok(Response.error());
		}
	}

    @GetMapping("/getAllUser")
    public Response<List<User>> getAllUser(@RequestParam(value = "userId")Long userId) {
        List<User> allUser = webSocket.getAllUser(userId);
        return new Response<>(200, "成功", allUser);
    }
}
